package com.zyc.studentstudy.utils

import android.text.TextUtils
import java.security.MessageDigest

/**
 * Description :
 * Author :mhwang
 * Date : 2017/8/7
 * Version : V1.0
 */
object Md5Util {

    private val hexDigits =
        arrayOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f")

    @JvmStatic
    fun str2MD5(str: String): String? {
        val md5: MessageDigest
        try {
            md5 = MessageDigest.getInstance("MD5")
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
        // 将字符串转换成字符串数组
        val pswdArray = str.toCharArray()
        val pswdByte = ByteArray(pswdArray.size)
        // 将字符转换成字节
        for (i in pswdArray.indices) {
            pswdByte[i] = pswdArray[i].toByte()
        }
        val digest = md5.digest(pswdByte)
        // 将得到的字节数组转换成十六进制数
        val buff = StringBuffer()
        for (b in digest) {
            val num = b.toInt() and 0xff
            // 如果不足16，加0填充
            if (num < 16) buff.append("0")
            buff.append(Integer.toHexString(num))
        }
        return buff.toString()
    }

    /** MD5加密
     * @param data 要加密的数据
     * @param encode 加密的编码
     * @return md5字符串
     */
    @JvmStatic
    fun str2MD5(data: String, encode: String): String? {
        var resultString: String? = null
        try {
            val md = MessageDigest.getInstance("MD5")
            resultString = if (TextUtils.isEmpty(encode)) {
                byteArrayToHexString(md.digest(data.toByteArray()))
            } else {
                byteArrayToHexString(md.digest(data.toByteArray(charset(encode))))
            }
        } catch (exception: Exception) {
        }
        return resultString
    }

    /** byte数组转换16进制字符串
     * @param b 要转换的byte数组
     * @return 16进制字符串
     */
    private fun byteArrayToHexString(b: ByteArray): String {
        val resultSb = StringBuffer()
        for (i in b.indices) {
            resultSb.append(byteToHexString(b[i]))
        }
        return resultSb.toString()
    }

    /** byte转换成16进制字符串
     * @param b 要转换的byte
     * @return byte对应的16进制字符串
     */
    private fun byteToHexString(b: Byte): String {
        var n = b.toInt()
        if (n < 0) n += 256
        val d1 = n / 16
        val d2 = n % 16
        return hexDigits[d1] + hexDigits[d2]
    }
}